package com.example.mask.maskmobilesshop.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mask.maskmobilesshop.constant.Constants;
import com.example.mask.maskmobilesshop.constant.HttpSchema;
import com.example.mask.maskmobilesshop.entity.vo.Request;
import com.example.mask.maskmobilesshop.entity.vo.Response;
import com.example.mask.maskmobilesshop.enums.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 发送短信工具类
 * 
 * @ClassName: SingleSendSms
 * @author: Xlh
 * @date 2017年1月18日 下午3:05:06
 */
public class SingleSendSms {
	private static Logger logger = LoggerFactory.getLogger(SingleSendSms.class.getName());
	
	private final static String APP_KEY = "23607477"; // AppKey从控制台获取
	private final static String APP_SECRET = "48c34870779c2ba62ffde582dc644e83"; // AppSecret从控制台获取
	private final static String SIGN_NAME = "CC邀请码"; // 签名名称从控制台获取，必须是审核通过的
	private final static String TEMPLATE_CODE = "SMS_58945003"; // 模板CODE从控制台获取，必须是审核通过的
	private final static String HOST = "sms.market.alicloudapi.com"; // API域名从控制台获取
	private final static String ERRORKEY = "errorMessage"; // 返回错误的key

	/**
	 * 发送短信
	 * 
	 * @Title: sendMsg
	 * @param: @param
	 *             phoneNum 目标手机号，多个手机号可以逗号分隔
	 * @param: @param
	 *             params
	 *             短信模板中的变量，数字必须转换为字符串，如短信模板中变量为${no}",则参数params的值为{"no":"123456"}
	 * @return: void
	 */
	public static boolean sendMsg(String phoneNum, String params) {
		Request request = new Request(Method.GET, HttpSchema.HTTP + HOST, "/singleSendSms", APP_KEY, APP_SECRET, Constants.DEFAULT_TIMEOUT);

		// 请求的query
		Map<String, String> querys = new HashMap<String, String>();
		querys.put("SignName", SIGN_NAME);
		querys.put("TemplateCode", TEMPLATE_CODE);
		querys.put("RecNum", phoneNum);
		querys.put("ParamString", params);
		request.setQuerys(querys);

		boolean result = false;
		try {
			Map<String, String> bodymap = new HashMap<String, String>();
			Response response = Client.execute(request);
			// 根据实际业务需要，调整对response的处理
			if (null == response) {
				logger.info("no response");
			} else if (200 != response.getStatusCode()) {
				logger.info("StatusCode:" + response.getStatusCode() + " ErrorMessage:" + response.getErrorMessage() + " RequestId:" + response.getRequestId());
			} else {
				bodymap = ReadResponseBodyContent(response.getBody());
				if (null != bodymap.get(ERRORKEY)) {
					// 当传入的参数不合法时，返回有错误说明
					logger.info(bodymap.get(ERRORKEY));
				} else {
					// 成功返回map，对应的key分别为：message、success等
					logger.info("发送成功:" + JSON.toJSONString(bodymap));
					result = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private static Map<String, String> ReadResponseBodyContent(String body) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			JSONObject jsonObject = JSON.parseObject(body);
			if (null != jsonObject) {
				for (Entry<String, Object> entry : jsonObject.entrySet()) {
					map.put(entry.getKey(), entry.getValue().toString());
				}
			}
			if ("false".equals(map.get("success"))) {
				map.put(ERRORKEY, map.get("message"));
			}
		} catch (Exception e) {
			map.put(ERRORKEY, body);
			e.printStackTrace();
		}
		return map;
	}
}
